<template>
  <ui-container :isCanScroll="isCanScroll" :isForm="true" :scrollGoTop="scrollGoTop" :scrollbar="false" @scroll="scroll">
    <view class="eleDetail" id="history" @click="handleCloseTips">
      <view class="header" id="eleDetailHeader" :style="{zIndex: showFilter ? '1' : '10'}">
        <!-- #ifndef H5 -->
        <view class="navBarTop">
          <global-nav-bar left-icon="back" :title="navBarTitle" @setHeight="setHeight" :fixed="false"
            backgroundColor="#2C2C2C" color="#fff" @clickLeft="handleBack"></global-nav-bar>
        </view>
        <!-- #endif -->

        <view class="content">
          <view class="header_content">
            <view class="top">
              <view class="left">
                <image src="@/static/images/index/eleIcon.png" mode=""></image>
                <view class="title">
                  <text @click="toProject(eleMsg.buildingId)">{{
                    eleMsg.buildingName
                  }}</text>
                  <text>{{
                    eleMsg.elevatorAddress
                  }}</text>
                </view>
              </view>
            </view>
            <view class="bottom">
              <view class="msgBox">
                <view class="itemTag msgBoxItem">
                  <view>
                    <text>{{
                      eleMsg.useType == 0 ? "年审梯" : "非年审梯"
                    }}</text>
                    <text class="line"></text>
                  </view>
                  <view>
                    <text>{{ eleMsg.driveModeName || "-" }}</text>
                    <text class="line"></text>
                  </view>
                  <view>
                    <text>{{ eleMsg.brandName || "-" }}</text>
                    <!-- <text class="line"></text> -->
                  </view>
                  <!-- <view>
										<text>{{ `${getYear(eleMsg.madeDate)}年` }}</text>
									</view> -->
                </view>
              </view>
              <view class="msgBox"
                v-if="!(eleMsg.elevatorUseType == '1441306947313549337' || eleMsg.elevatorUseType == '1441306947313549330')">
                <view class="slect" @tap="searchPart">
                  <text style="display: inline-block;width: 80%;" v-if="partMsg.name != '整梯'">{{
                    partMsg.routeNmae
                  }} <text v-if="flagMsg.id">({{ flagMsg.routeNmae }})</text> </text>
                  <text class="holder" v-else>请选择零部件查看具体零部件数据</text>
                  <view class="choice">
                    <text>选择</text>
                    <uni-icons type="arrowright" size="16" color="#0091FF"></uni-icons>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="tabs">
            <view v-for="(item, index) in tabList" :key="index" :class="['tabs-item', tabIdx == item.ids ? 'act' : '']"
              @click="handleClickTab(item)">
              {{ item.name }}
              <view class="line" v-if="tabIdx == item.ids"></view>
            </view>
          </view>
          <view v-if="tabIdx === 2" class="search-actions-wrapper">
            <view class="search-bar">
              <uni-search-bar
                  class="uni-search-bar"
                  v-model="keyword"
                  clearButton="auto"
                  cancelButton="none"
                  placeholder="请输入配件类型/项目名称/任务ID"
                  @blurs="handleSearchPart"
              />
            </view>
          </view>
          <!-- header end -->
        </view>
      </view>
      <tk-screen-scroll :list="tabList" @getActIdx="getActIdx" :active="tabIdx" :isOnlytkScreen="true" :height="230">
        <!-- 健康数据 -->
        <healthData :elevatorId="elevatorId" :partMsg="partMsg" :flagMsg="flagMsg" :eleMsg="eleMsg" v-show="tabIdx === 0"></healthData>
        <!-- 维保历史 -->
        <historyList ref="historyList" :elevatorId="elevatorId" v-if="tabIdx === 1" :partsId="partMsg.id" :stickyTop="stickyTop" :flagMsg="flagMsg"
                     @changeTab="changeTab" :outTab="tabIdx" @showFilterChange="showFilterChange"></historyList>
        <!-- 配件进度 -->
        <view v-show="tabIdx === 2">
          <scroll-view
            class="scrollBox"
            :scroll-y="true"
            :refresher-enabled="isAllowRefresh"
            :refresher-triggered="triggered"
            scroll-with-animation
            @scrolltolower="scrolltolower"
            @refresherrefresh="onRefresh"
            @scroll="handleScroll"
            :scroll-top="partsScrollTop"
          >
            <view class="part-main">
              <partsList isMy :listData="partsListData" :styleSate="true" @toPage="toRepairDetail" />
              <uni-load-more
                v-if="isStateMore"
                :status="loadStatus"
                :contentText="contentText"
              ></uni-load-more>
              <!-- 暂无数据 -->
              <view class="empty" v-if="!partsListData.length">
                <image src="@/static/images/index/empty1.png" mode=""></image>
                暂无数据
              </view>
            </view>
          </scroll-view>
        </view>
          <!-- 实时信息 -->
        <elevatorLive :elevatorId="elevatorId" v-if="tabIdx === 3"></elevatorLive>
        <!-- 整梯基础信息 -->
        <elevatorInfos v-if="partMsg.id == 0 && tabIdx === 4" :isElevatorId="elevatorId" />
        <!-- 部件基础信息 -->
        <basicInformation v-if="partMsg.id != 0 && tabIdx === 4" :elevatorId="elevatorId" :partMsg="partMsg" :flagMsg="flagMsg" />
        <!-- 保养计划 -->
        <mainPlanCom v-if="tabIdx === 5" :elevatorId="elevatorId" @handleFilterDrawerShow="handleFilterDrawerShow" />
      </tk-screen-scroll>
      <previewMedia ref="previewMedia"></previewMedia>
    </view>
  </ui-container>
</template>

<script>
import UiContainer from '@/components/ui-container/ui-container';
import GlobalNavBar from '@/components/uni-nav-bar/global-nav-bar';
import healthData from './components/healthData.vue';

import elevatorInfos from './maintains/elevator-info.vue';
import basicInformation from './components/basicInformation.vue';
import mainPlanCom from './components/mainPlanCom.vue';
import historyList from './components/historyList.vue';
import elevatorLive from './components/elevatorLive.vue';
import { elevtorDetail, elevtorMantles } from '@/apis/elevator.js';
import { getDiffYear } from '@/utils/tools.js';
import { hanleToken } from '@/utils/utils.js';
import { mapState } from 'vuex';
import TkScreenScroll from '@/components/tk-screen-scroll/index';
import partsList from '@/components/partsList/partsList.vue';
import { partsNewMyList } from '@/apis/parts.js';
export default {
	components: {
		partsList,
		elevatorLive,
		GlobalNavBar,
		UiContainer,
		healthData,
		elevatorInfos,
		basicInformation,
		mainPlanCom,
		historyList,
		TkScreenScroll,
	},
	computed: {
		...mapState('user', ['userinfo']),
		mH() {
			return 'calc(100vh - 100px)';
			// return `calc(100vh - ${this.mheight}px)`
		},
	},
	data() {
		return {
			// 默认选中整梯
			partMsg: { id: 0, name: '整梯' },
			flagMsg:{},
			cardList: [
				{
					// 隐患
					perilous: 1,
					label: '外观/清洁',
					score: 80,
				},
				{
					// 隐患
					perilous: 1,
					label: '功能/调整',
					score: 60,
				},
				{
					// 隐患
					perilous: 1,
					label: '润滑',
					score: 100,
				},
				{
					// 隐患
					perilous: 1,
					label: '测量',
					score: 100,
				},
			],
			tabList: [
				{ name: '健康数据', ids: 0 },
				{ name: '维保历史', ids: 1 },
				{ name: '配件进度', ids: 2 },
				{ name: '实时信息', ids: 3 },
				{ name: '基础信息', ids: 4 },
				{ name: '保养计划', ids: 5 },
			],
			tabIdx: 0,
			// 顶部导航栏 title
			navBarTitle: '电梯详情',
			mheight: 0,
			// 电梯责任人
			mantles: [],
			// 滚动距离
			scrollTop: 0,
			scrollGoTop: 0,
			elevatorId: '',
			eleMsg: {},
			title: '',
			list: [],
			dateObj: {
				startTime: '',
				endTime: '',
				value: '',
				planBeginDate: '',
				planEndDate: '',
			},
			isCanScroll: true,
			typeIndex: 1,
			mheights: 0,
			// 子组件粘黏属性的高度
			stickyTop: 0,
			// 点击锁
			isLock: false,
			showFilter: false, // 是否显示筛选
			partsListData: [], // 配件列表数据
			keyword: '', // 配件搜索关键词
			partsParams: {
				current: 1,
				size: 10
			},
			loadStatus: 'loading',
			isLoadMore: false,
			// 配件列表相关
			partsScrollTop: 0,
			isAllowRefresh: true,
			triggered: false,
			contentText: {
				contentdown: '上拉显示更多',
				contentrefresh: '正在加载...',
				contentnomore: '没有更多了'
			},
			isStateMore: false,
			totalCount: 0,
		};
	},
	created() {
		const query = uni.createSelectorQuery();
		query.select('#eleDetailHeader').boundingClientRect();
		query.exec((res) => {
			console.log(res[0]);
			this.stickyTop = parseInt(res[0].height);
		});
	},
	onLoad(e) {
		uni.getSystemInfo({
			success: (res) => {
				this.mheights = res.windowHeight - 78 - 240;
				// console.log(res,this.safeAreaBottom,666)
			},
		});
		this.elevatorId = e.id;
		setTimeout(()=>{
			this.tabIdx = Number(e.type) || 0;
			if (Number(e.toMain)) {
				this.tabIdx = 1;
				setTimeout(() => {
					this.$refs['historyList'].$refs['part-order-list'].handleClickTab(0,1);
				}, 200);
			}
		},200);
		this.fetchEleDetail();
	},
	onReady() { },
	onShow() {
		if (this.scrollTop != 0 && this.tabIdx != 3) {
			this.scrollGoTop = 1;
			this.$nextTick(() => {
				this.scrollGoTop = 0;
			});
		}
		this.flagMsg  = {};
		if (uni.getStorageSync('componentSelect')) {
			this.partMsg = uni.getStorageSync('componentSelect');
		}
		if (uni.getStorageSync('templateSelect')) {
			this.partMsg = uni.getStorageSync('templateSelect').slect;
			this.flagMsg = uni.getStorageSync('templateSelect').flag;
		}
	},
	onUnload() {
		hanleToken('remove', 'componentSelect');
		hanleToken('remove', 'templateSelect');
	},
	onHide() {
		hanleToken('remove', 'componentSelect');
		hanleToken('remove', 'templateSelect');
	},
	watch: {
		partMsg(val) {
			if (val.id != 0) {
				// 这里是零配件
				this.tabList = [
					{ name: '健康数据', ids: 0 },
					{ name: '维保历史', ids: 1 },
					{ name: '基础信息', ids: 3 },
				];
				if (this.tabIdx === 4 || this.tabIdx === 2) {
					this.handleClickTab({ ids: 0 });
				}
				if (this.tabIdx === 3) {
					this.handleClickTab({ ids: 3 });
				}
			} else {
				// 整梯
				this.tabList = [
					{ name: '健康数据', ids: 0 },
					{ name: '维保历史', ids: 1 },
					{ name: '配件进度', ids: 2 },
					{ name: '实时信息', ids: 3 },
					{ name: '基础信息', ids: 4 },
					{ name: '保养计划', ids: 5 },
				];
			}
		},

	},
	methods: {
		// 切换保养维修返回顶部
		changeTab() {
			if (this.scrollTop != 0) {
				this.scrollGoTop = 1;
				this.$nextTick(() => {
					this.scrollGoTop = 0;
				});
			}
		},
		// 跳转 选择零部件
		searchPart() {
			if (!this.isLock) {
				this.isLock = true;
				uni.navigateTo({
					url: '/pageModules/projectInfo/componentsDetail/assignComponent?partMsg=' +
            JSON.stringify(this.partMsg) + '&elevatorId=' + this.elevatorId
				});
				setTimeout(() => {
					this.isLock = false;
				}, 2000);
			}
		},
		// 跳转 项目详情
		toProject(id) {
			uni.navigateTo({
				url: '/pageModules/projectInfo/detail?id=' + id,
			});
		},
		setHeight(n) {
			this.mheight = n;
			console.log('n', n);
		},
		// 滑动切换
		getActIdx(idx, arrow) {
			this.tabIdx = idx;

			if (this.partMsg.id != 0) {
				if (idx === 0) {
					this.tabIdx = 0;
				}
				if (idx === 1) {
					this.tabIdx = 1;
				}
				if (idx === 2) {
					this.tabIdx = 3;
				}
				if (this.tabIdx >= 3 && arrow === 'right') {
					this.tabIdx = 1;
				}
				if (idx >= 3 && arrow === 'left') {
					this.tabIdx = 3;
				}
			}
		},
		scroll(e) {
			let that = this;
			// 获取元素距顶距离
			const query = uni.createSelectorQuery();
			query.select('#history').boundingClientRect();
			query.selectViewport().scrollOffset();
			query.exec(function (res) {
				if (Math.abs(res[0].top) >= that.mheight) {
					that.navBarTitle = that.eleMsg.elevatorAddress;
				} else {
					that.navBarTitle = '电梯详情';
				}
			});
			this.scrollTop = e.detail.scrollTop;
		},
		handleCloseTips() {
			// eslint-disable-next-line vue/custom-event-name-casing
			uni.$emit('tooltipsClose');
		},
		// 切换tab
		handleClickTab(item) {
			console.log(item, 333);
			this.tabIdx = item.ids;
			if (this.scrollTop != 0) {
				this.scrollGoTop = 1;
				this.$nextTick(() => {
					this.scrollGoTop = 0;
				});
			}
			// 切换到配件进度tab时加载数据
			if (item.ids === 2) {
				this.partsParams.current = 1;
				this.partsListData = [];
				this.loadPartsList();
			}
		},
		// 计算年限
		getYear(d) {
			return d ? getDiffYear(d) : '-';
		},
		// 获取电梯详情 及责任人
		fetchEleDetail() {
			elevtorDetail({ elevatorId: this.elevatorId }).then((res) => {
				if (res) {
					this.eleMsg = res.data;
				}
			});
			elevtorMantles({ elevatorId: this.elevatorId }).then((res) => {
				if (res) {
					this.mantles = res.data;
				}
			});
		},
		showFilterChange(val) {
			// #ifdef H5
			this.showFilter = val;
			// #endif
		},
		handleFilterDrawerShow(val) {
			console.log('handleFilterDrawerShow',val);
			this.showFilter = val;
		},
		// 配件搜索
		handleSearchPart() {
			if (!this.keyword) return;
			this.partsParams.current = 1;
			this.partsListData = [];
			this.loadPartsList();
		},

		// 配件列表滚动
		handleScroll(e) {
			if (e.target.scrollTop > 100) {
				this.isAllowRefresh = false;
			} else {
				this.isAllowRefresh = true;
			}
		},

		// 配件列表下拉刷新
		onRefresh() {
			console.log('下拉刷新');
			this.triggered = true;
			this.partsParams.current = 1;
			this.partsListData = [];
			this.loadPartsList();
		},

		// 配件列表上拉加载
		scrolltolower() {
			if (this.partsParams.current * this.partsParams.size < this.totalCount) {
				this.partsParams.current += 1;
				this.loadPartsList();
			} else {
				this.loadStatus = 'noMore';
			}
		},

		// 加载配件列表
		loadPartsList() {
			const params = {
				...this.partsParams,
				elevatorId: this.elevatorId
			};
			if (this.keyword) {
				params.keyword = this.keyword;
			}
			this.loadStatus = 'loading';
			uni.showLoading({
				title: '加载中'
			});
			partsNewMyList(params).then(res => {
				if (res.code === 200) {
					const arr = res.data.records || [];
					// 处理配件信息
					arr.forEach(item => {
						item.num = item.partsNum ? item.partsNum : '';
						if (item.skuPartsInfo) {
							let skuPartsInfo = item.skuPartsInfo;
							if (!Array.isArray(skuPartsInfo) && skuPartsInfo.skuItemList) {
								skuPartsInfo = skuPartsInfo.skuItemList;
							} else {
								item.skuPartsInfo = [];
							}
							let skuPartsInfoArr = [];
							if (Array.isArray(skuPartsInfo)) {
								skuPartsInfo.forEach(v => {
									if (v.label !== '配件名称') {
										skuPartsInfoArr.push(`${v.label}:${v.value}${v.unitName ? `(${v.unitName})` : ''}`);
									} else {
										item.categoryInfo = v.value;
									}
								});
								item.partsModel = skuPartsInfoArr.join('；');
							}
						}
					});
					this.totalCount = res.data.total;
					this.partsListData = this.partsListData.concat(arr);
					if (arr.length < this.partsParams.size) {
						this.loadStatus = 'noMore';
					}
					this.triggered = false;
					this.isStateMore = res.data.pages !== 1;
				}
				uni.hideLoading();
			});
		},

		// 上拉加载更多
		onReachBottom() {
			if (this.tabIdx === 2 && !this.isLoadMore) {
				this.isLoadMore = true;
				this.partsParams.current += 1;
				this.loadPartsList();
			}
		},
		// 配件申请
		toRepairDetail(obj) {
			uni.navigateTo({
				url: '/subpages/approve/partApprovalDetail?type=1&id=' + obj.planId,
			});
		},
	},
};
</script>
<style>
page {
  background-color: #f6f5f8;
}
</style>
<style lang="scss" scoped>
.tabs {
  background-color: #ffffff;
  display: flex;
  border-bottom: 2rpx #eee solid;
  height: 86rpx;
  overflow-x: auto;
  &-item {
    height: 100%;
    display: flex;
    align-items: center;
    margin: 0 20rpx;
    font-size: 26rpx;
    font-weight: 400;
    color: #93b1c7;
    transition: 0.4s all;
    position: relative;
    white-space: nowrap;
  }

  .line {
    width: 100%;
    height: 4rpx;
    background: #0091ff;
    border-radius: 4rpx;
    transition: 0.4s all;
    position: absolute;
    bottom: 0;
    left: 0;
  }

  .act {
    font-weight: bold;
    color: #0091ff;
    border-color: #0091ff;
    font-size: 30rpx;
  }
}
.eleDetail {
  background: #f3f6f8;
  // min-height: 100vh;
  position: relative;
  height: auto;
  // padding-bottom: 100rpx;

  .empty {
    display: flex;
    align-items: center;
    justify-content: center;

    image {
      width: 64rpx;
      height: 64rpx;
    }

    height: 800rpx;
    flex-direction: column;
  }

  .header {
    background-color: #f3f6f8;
    position: sticky;
    top: 0;
    left: 0;
    z-index: 10;

    .header_content {
      padding: 34rpx 20rpx 20rpx 28rpx;
      background: #fff;
      margin-bottom: 20rpx;

      .top {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
          width: 560rpx;
          // display: flex;
        }

        .left {
          display: flex;
          .title{
            text:nth-child(2){
              margin-left: 20rpx
            }
          }

          image {
            width: 48rpx;
            height: 48rpx;
            margin-right: 12rpx;
          }

          .tag {
            padding: 0rpx 8rpx;
            font-size: 24rpx;
            border-radius: 4rpx;
            border: 1rpx solid;
            white-space: nowrap;
          }

          .red {
            color: #e02020;
            border-color: #e02020;
          }

          .green {
            color: #16bf99;
            border-color: #16bf99;
          }
        }

        .right {
          color: #666;
          font-size: 24rpx;
          display: flex;
          position: absolute;
          right: 28rpx;
          top: 40rpx;
          width: 120rpx;
          justify-content: flex-end;
          height: 44rpx;
          // align-items: center;
          height: 80rpx;

          image {
            width: 28rpx;
            height: 28rpx;
          }
        }
      }

      .bottom {
        .msgBox {
          padding-left: 60rpx;
          font-size: 24rpx;
          color: #666;

          .slect {
            background: #f6f6f6;
            border-radius: 4px;
            padding: 8rpx 0;
            padding-left: 20rpx;
            padding-right: 10rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .holder{
              color:#666;
            }
            .choice{
              font-size: 24rpx; 
              color: #0091ff
            }
          }

          .msgBoxItem {
            margin-bottom: 8rpx;
          }

          .itemTag {
            display: flex;

            view {
              height: 32rpx;

              display: flex;
              padding-right: 24rpx;
              position: relative;
            }

            .line {
              width: 2rpx;
              height: 22rpx;
              background-color: #ccc;
              display: flex;
              position: absolute;
              right: 10rpx;
              top: 6rpx;
            }
          }

          .more {
            display: flex;
            color: #0091ff;
            margin-bottom: 16rpx;
          }
        }

        .addressBox {
          margin-left: 60rpx;

          // height: 108rpx;
          background: #f6f6f6;
          border-radius: 8rpx;
          font-size: 24rpx;
          padding: 20rpx 0 16rpx 16rpx;
          font-size: 24rpx;
          color: #999;

          .top {
            display: flex;

            .name {
              display: flex;
              // padding-left: 14rpx;
              font-weight: 600;
              color: #333;
              align-items: center;
            }

            image {
              width: 32rpx;
              height: 32rpx;
            }
          }

          .buildAddress {
            padding: 0 20rpx 0 32rpx;
            margin-left: 10rpx;
          }
        }
      }
    }
  }
}
.search-actions-wrapper {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  padding: 16rpx 20rpx;
  //margin-bottom: 20rpx;

  .search-bar {
    flex: 1;
    margin-right: 16rpx;

    .uni-search-bar {
      padding: 0;

      /deep/ .uni-searchbar {
        padding: 0;
      }

      /deep/ .uni-searchbar__box {
        height: 64rpx;
        background-color: #f6f6f6 !important;
        border-radius: 32rpx;
        border: 0;
      }

      /deep/ .uni-searchbar__text-placeholder {
        font-size: 26rpx;
        color: #999;
      }

      /deep/ .uni-input-input {
        font-size: 26rpx;
      }
    }
  }

  .actions {
    display: flex;
    align-items: center;
    color: #666;
    font-size: 26rpx;

    .action-item {
      display: flex;
      align-items: center;
      margin-left: 24rpx;

      .action-icon {
        width: 32rpx;
        height: 32rpx;
        margin-right: 4rpx;
      }

      uni-icons {
        margin-right: 4rpx;
      }

      &.active {
        text {
          color: #0091FF;
        }
      }
    }
  }
}
.scrollBox {
  height: calc(100vh - 450rpx);
}

.empty {
  display: flex;
  justify-content: center;
  width: 100%;
  
  image {
    width: 64rpx;
    height: 64rpx;
    margin-bottom: 20rpx;
  }

  color: #999;
  flex-direction: column;
  align-items: center;
  padding-top: 300rpx;
  font-size: 24rpx;
}

.part-main {
  padding: 20rpx;
  min-height: calc(100vh - 450rpx);
}
</style>
